import Icon from '@/components/Icon'
import { useInitialState } from '@/hooks'
import { getUserChannel } from '@/store/actions/home'
import { Tabs } from 'antd-mobile'
import { useState } from 'react'
import { Popup } from 'antd-mobile'

import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/types/store'
// 频道子组件
import Channels from './components/Channels'
// 文章列表子组件
import ArticleList from './components/ArticleList'
import { useHistory } from 'react-router-dom'

const Home = () => {
  // 1. 获取频道数据
  const { userChannel } = useInitialState(getUserChannel, 'home')
  // 2. 编辑用户频道
  const [visible, setVisible] = useState(false)
  const onChannelOpen = () => {
    setVisible(true)
  }
  const onChannelClose = () => {
    setVisible(false)
  }

  // 3. 手动控制切换tab高亮
  const dispatch = useDispatch()
  const { channelActiveKey } = useSelector((state: RootState) => state.home)

  const onTabChange = (key: string) => {
    dispatch({ type: 'home/changeTab', payload: key })
  }
  const history = useHistory()
  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      {userChannel.length > 0 && (
        <Tabs
          className="tabs"
          activeLineMode="fixed"
          onChange={onTabChange}
          activeKey={channelActiveKey}>
          {userChannel.map((item) => (
            <Tabs.Tab forceRender title={item.name} key={item.id}>
              {/* {`推荐频道的内容:${item.id}`} */}
              <ArticleList channel_id={channelActiveKey} />
            </Tabs.Tab>
          ))}
        </Tabs>
      )}
      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={onChannelOpen} />
      </div>
      {/* 编辑频道弹出层 */}
      <Popup visible={visible} position="left" className="channel-popup">
        <Channels onClose={onChannelClose} />
      </Popup>
    </div>
  )
}

export default Home
